package cn.com.xy.sms.sdk.service.pubId;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.ParsePhonePubIdManager;
import cn.com.xy.sms.sdk.db.entity.ContactsColumns;
import cn.com.xy.sms.sdk.db.entity.IccidInfo;
import cn.com.xy.sms.sdk.db.entity.IccidInfoManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.iccid.IccidLocationUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetUtil;
import cn.com.xy.sms.sdk.net.NewXyHttpRunnable;
import cn.com.xy.sms.sdk.net.util.ServerUtil;
import cn.com.xy.sms.sdk.queue.SdkTaskQueue;
import cn.com.xy.sms.sdk.queue.TaskInfo;
import cn.com.xy.sms.sdk.util.DuoquUtils;
import cn.com.xy.sms.sdk.util.JsonUtil;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XyUtil;

public class ParsePhonePubIdService {
	
	public static final int RESULT_TOKEN_FLASH = 403;//token过期
	public static final int RESULT_SERVER_ERROR = 404;//服务器错误
	public static final int RESULT_NO_NET = 405;//没有网络
	public static final int RESULT_SUCESS = 200;//成功返回
	public static String PHONE_PUBID_UPDATE_STEP = "10";
	


	/*
	 * 批量更新接口
	 */
	public static void batchUpdatePubId() {

		try {
				JSONArray qureyJsonArray = null;
				long queryTime = checkQueryUpdateCycle(OnlineUpdateCycleConfigInterface.TYPE_QUERY_BATCH_PHONE_NULL_PUB_ID_UPDATE_CYCLE, ContactsColumns.UPDATE_CYCLE);
				qureyJsonArray = ParsePhonePubIdManager.queryPubIdByDateAndUpdate(queryTime,  PHONE_PUBID_UPDATE_STEP, true);
				int cnt = 0;
				while (!StringUtils.isNull(qureyJsonArray.toString()) && qureyJsonArray.length() != 0) {
					queryPubIdByNet(qureyJsonArray);
					qureyJsonArray = ParsePhonePubIdManager.queryPubIdByDateAndUpdate(queryTime,  PHONE_PUBID_UPDATE_STEP, true);
					cnt++;
					if(cnt > 1000){
						break;
					}
					Thread.sleep(1);
				}
				//  更新失败的情况下，标记位还原
            /* SDK-499 hewegnao 20160621 start */
            ParsePhonePubIdManager.updateQueryFlag(true);
            /* SDK-499 hewegnao 20160621 end */
				
				long queryTime1 = checkQueryUpdateCycle(OnlineUpdateCycleConfigInterface.TYPE_QUERY_BATCH_PHONE_PUB_ID_UPDATE_CYCLE, ContactsColumns.UPDATE_CYCLE);
				qureyJsonArray = ParsePhonePubIdManager.queryPubIdByDateAndUpdate(queryTime1,  PHONE_PUBID_UPDATE_STEP, false);
				cnt = 0 ;
				while (!StringUtils.isNull(qureyJsonArray.toString()) && qureyJsonArray.length() != 0) {
					queryPubIdByNet(qureyJsonArray);
					qureyJsonArray = ParsePhonePubIdManager.queryPubIdByDateAndUpdate(queryTime1,  PHONE_PUBID_UPDATE_STEP, false);
					cnt++;
					if(cnt > 1000){
						break;
					}
					Thread.sleep(1);
				}
            // 更新失败的情况下，标记位还原
            /* SDK-499 hewegnao 20160621 start */
            ParsePhonePubIdManager.updateQueryFlag(true);
            /* SDK-499 hewegnao 20160621 end */
		} catch (Throwable e) {
			// TODO: handle exception
			LogManager.e(Constant.TAG, "batchUpdatePubId: ", e);
		}
		// }

	}
	
	
//	public static void  recoverDateBase(){
//		ParsePhonePubIdManager.queryAndUpdateQueryFlag();
//	}
 
	
	/*
	 * 网上批量更新
	 */
	
	
	public static void queryPubIdByNet(JSONArray newjsonArray) {
		if (newjsonArray.length() == 0){
			return;
		}
		try {
		    StringBuffer areaCodeCard = new StringBuffer();
			getAreaCode(areaCodeCard);
			if(!NetUtil.hasNewToken(null)){
			    LogManager.e("xiaoyuan", "queryPubIdByNet not hasNewToken");
			    return;
			}
			
			final String dataString = ServerUtil.getQueryPubIdReq(areaCodeCard.toString(), newjsonArray);
			if (!StringUtils.isNull(dataString)) {
                /* SDK-526 huangzhiqiang 20160713 start */
                NetUtil.requestNewTokenIfNeed(null);
                final String token = NetUtil.getToken();
                /* SDK-526 huangzhiqiang 20160713 end */
				XyCallBack reqcallBack = new XyCallBack() {

					@Override
					public void execute(Object... obj) {
						if (obj != null && obj.length > 0) {
							String resultCode = obj[0].toString();
							if (resultCode.equals(NewXyHttpRunnable.ERROR_CODE_TOKEN_FAILED)) {
                                /* SDK-526 huangzhiqiang 20160713 start */
                                NetUtil.requestNewTokenAndPostRequestAgain(NetUtil.URL_PUB_NUMBER, dataString,
                                        Constant.FIVE_MINUTES, false, false, true, null, token, this);
                                return;
                                /* SDK-526 huangzhiqiang 20160713 end */
//								recoverDateBase();
//								XyUtil.doXycallBackResult(null, null,
//										RESULT_TOKEN_FLASH);
							} 

							if (resultCode
									.equals(NewXyHttpRunnable.ERROR_CODE_PARE_ERR)
									|| resultCode
											.equals(NewXyHttpRunnable.ERROR_CODE_SERVICE_ERR)) {
								// 网络失败
//								recoverDateBase();
//								XyUtil.doXycallBackResult(null, null,
//										RESULT_NO_NET);
							} else {
								if (resultCode.equals("0") && obj.length == 2) {
									String response = obj[1].toString();
									if (StringUtils.isNull(response)) {
//										recoverDateBase();
										XyUtil.doXycallBackResult(null, null, RESULT_SERVER_ERROR);
									} else {
										try {
											JSONArray jsonArray = new JSONArray(response);
											 // 入库并放入缓存
											ParsePhonePubIdManager.saveOrUpdate(jsonArray);
//											ParsePhonePubIdManager.insertCatch(jsonArray);
											// 更新查询时间
											ParsePhonePubIdManager.updateQueryFlag(true);
										} catch (Exception e) {
											// e.printStackTrace();
//											recoverDateBase();
											LogManager.e(Constant.TAG, "checkValidUrlNetBatch: ", e);
											XyUtil.doXycallBackResult(null, null, RESULT_SERVER_ERROR);

										}
									}
								} else {
//									recoverDateBase();
//									XyUtil.doXycallBackResult(null, null,
//											RESULT_SERVER_ERROR);
								}
							}
						} else {
//							recoverDateBase();
//							XyUtil.doXycallBackResult(null, null,
//									RESULT_SERVER_ERROR);
						}
					}

				};
				 NetUtil.executeNewServiceHttpRequest(NetUtil.URL_PUB_NUMBER, dataString, reqcallBack,false,false, true,null);
			}
		} catch (Exception e) {
			LogManager.e(Constant.TAG, "checkValidUrlNet: ", e);

		}
	}
	
	/**
	 * 网络查询
	 */
	public static void queryPubIdService(String phoneNum,  String dbresoult){
//	    LogManager.e("xiaoyuan", "phoneNum: "+phoneNum+" dbresoult: "+dbresoult);
		if ("true".equalsIgnoreCase(dbresoult)){
			try {
				HashMap<String, String> map = new HashMap<String, String>();
				
				map.put("pubId", "");
				map.put("phone", phoneNum);
				map.put("querytime", "0");
				map.put("queryflag", "0");
				ParsePhonePubIdManager.saveOrUpdateSingleDate(map);
			} catch (Exception e) {
				// TODO: handle exception
				LogManager.e(Constant.TAG, "queryPubIdFromNet: ", e);
			}
		}
        /* SDK-499 hewengao 20160621 start */
        if (NetUtil.isEnhance() && NetUtil.checkAccessNetWork(1)) {// wifi环境下，才可以批量更新
            /* SDK-499 hewengao 20160621 end */
            IccidLocationUtil.queryAreaCode(true);// 网络获取省份域码，同步操作
            batchUpdatePubId();
        }

	}
	
	/**
	 * 查询依据号码获取脚本公众号ID入口
	 * 
	 * */
	public static String queryPubIdByPhoneNum(String phoneNum) {
		String value = null;
		String cacheValue = null;//缓存值
		JSONObject resoult = null;
		String result = "false";//返回结果
		 LogManager.d("xiaoyaun", "#########queryPubIdByPhoneNum : ",phoneNum);
		if (phoneNum   == null) {
			return null;
		}
		try {
			cacheValue = ParsePhonePubIdManager.getPubIdByCache(phoneNum);//先查询缓存
			if (!StringUtils.isNull(cacheValue)) {
				result = "false";
				return cacheValue;
			}
				resoult = ParsePhonePubIdManager.queryPubId(phoneNum);//查数据库
				if (resoult == null){//数据库无记录
					result = "true";
					return null;
				}else{
					ParsePhonePubIdManager.setPubIdByCache(resoult.getString("phone"), resoult.getString("pubId"));
					value = resoult.getString("pubId");
					result = "false";
					if (StringUtils.isNull(value)){//数据库中pubid为空
						return null;
					}else{
						return value;
					}
				}
		} catch (Throwable e) {
			LogManager.e(Constant.TAG, "queryPubIdByPhoneNum: ", e);
		}finally{
//		    LogManager.e("xiaoyaun", "#########queryPubIdByPhoneNum phoneNum: "+phoneNum+"   dbresoult: "+result );
			SdkTaskQueue.addTask(new TaskInfo(13, "phoneNum", phoneNum, "dbresoult", result ));
		}
		return null;
	}
	
	


    private static long checkQueryUpdateCycle(int cycleType, long defaultCycle) {

        long time = DexUtil.getUpdateCycleByType(cycleType, defaultCycle);
        return (System.currentTimeMillis() - time);
    }


	
	/**
	 *从卡中获取区域码 
	 */
	private static String getCardAreaCode(int simIndex){
		JSONObject res = null;
		 res = DuoquUtils.getSdkDoAction().getProviceAndSP(simIndex);
         try {
             if (res == null) {
                 IccidInfo icc = IccidInfoManager.queryDeftIccidInfo(Constant.getContext());
                 if (icc != null) {                
                     return icc.areaCode;
                 }
             } else {
                 String p = (String) JsonUtil.getValueFromJsonObject(res, "provice");
                 String pcode = IccidInfoManager.getProviceCode(p);
                 if (pcode != null) {
                	 return pcode;
                 }
             }
         } catch (Throwable e) {
             LogManager.e(Constant.TAG, "getCardAreaCode: ", e);
         }
         return null;
	}
	
	/**
	 *拼接获取区域码 
	 */
	private static void getAreaCode(StringBuffer areaCodeCard){
		StringBuffer areaCodeCard1 = new StringBuffer();
		StringBuffer areaCodeCard2 = new StringBuffer();
		areaCodeCard1= areaCodeCard1.append(getCardAreaCode(0));
		areaCodeCard2= areaCodeCard2.append(getCardAreaCode(1));
		if (StringUtils.isNull(areaCodeCard1.toString()) && StringUtils.isNull(areaCodeCard2.toString())){
			areaCodeCard.append("CN");
		}else if (StringUtils.isNull(areaCodeCard1.toString()) && !StringUtils.isNull(areaCodeCard2.toString())){
			areaCodeCard.append(areaCodeCard2.toString());
		}else if (StringUtils.isNull(areaCodeCard2.toString()) && !StringUtils.isNull(areaCodeCard1.toString())){
			areaCodeCard.append(areaCodeCard1.toString());
		}else{
			areaCodeCard.append(areaCodeCard1.toString()).append(",").append(areaCodeCard2.toString());
		}
	}
	
}
